/**
 * 获取查询参数
 *
 * @param {*} search
 */
export const getSearchParams = (search = '') => {
  const searchParams = {};

  if (search) {
    const params = search.slice(search.indexOf('?') + 1).split('&');
    for (let i = 0, len = params.length; i < len; i++) {
      const item = params[i].split('=');
      searchParams[item[0]] = item[1];
    }
  }

  return searchParams;
};

/**
 * 获取地址栏查询参数
 */
export const getQueryParams = () => {
  let queryParams = {
    ...getSearchParams(window.location.search),
    ...getSearchParams(window.location.hash),
  };
  // 当启用统一认证时，还需要从统一认证的service参数中提取参数
  if (queryParams.appid && queryParams.service) {
    const service = window.decodeURIComponent(window.decodeURIComponent(queryParams.service));
    const length = service.length;
    const start = service.indexOf('index.html?');
    const end = service.indexOf('#');
    if (start != -1) {
      const search = service.substring(start, end != -1 ? end : length);
      queryParams = {
        ...queryParams,
        ...getSearchParams(search),
      };
    }
  }
  return queryParams;
};

export const isEMClient = () => {
  const ua = window.navigator.userAgent;
  const isEM = ua && ua.indexOf('E-Mobile') > -1;
  return isEM;
};

export const getClient = (props = {}) => {
  const { location = {} } = props;
  const { search = '' } = location;
  const params = getSearchParams(search);
  if (params.client) {
    return params.client;
  } else {
    const ua = window.navigator.userAgent;
    const isEM = ua && ua.indexOf('E-Mobile') > -1;
    const isPCEM = isEM && ua.indexOf('Electron') > -1;
    return isEM && !isPCEM ? 'mobile' : 'pc';
  }
};
